package com.forum.Controller;

import com.common.Entity.Result;
import com.common.Utils.JwtUtil;
import com.forum.Entity.Topic;
import com.forum.Service.TopicService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/topic")
public class TopicController {
    @Autowired
    private TopicService topicService;
    @GetMapping("/getTopicList")
    public Result getTopicList(@RequestParam Integer pageNum,
                               @RequestParam Integer pageSize,
                               @RequestParam(required = false) String topicName,
                               @RequestParam(required = false) String token){
        if (!Objects.equals(token, "")) {
            String username = JwtUtil.extractUsername(token);
            if (username == null) {
                return Result.error("无效的token");
            }
            PageInfo<Topic> pageInfo = topicService.getTopicListByThree(pageNum, pageSize, topicName, username);
            return Result.success(pageInfo);
        }
        PageInfo<Topic> pageInfo = topicService.getTopicList(pageNum, pageSize, topicName);
        return Result.success(pageInfo);
    }
    @GetMapping("/getTopicLists")
    public Result getTopicLists(){
        List<Topic> list= topicService.getTopicLists();
        return Result.success(list);
    }
    @PostMapping("/addTopic")
    public Result addTopic(@RequestBody Topic topic){
        topicService.addTopic(topic);
        return Result.success();
    }

    @PutMapping("/updateTopic")
    public Result updateTopic(@RequestBody Topic topic){
        topicService.updateTopic(topic);
        return Result.success();
    }

    @DeleteMapping("/deleteTopic/{topicId}")
    public Result deleteTopic(@PathVariable("topicId") String topicId){
        topicService.deleteTopic(topicId);
        return Result.success();
    }
}
